package com.monkey.demolist.greendao.one;

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.monkey.demolist.R;
import com.monkey.demolist.greendao.n.DaoMaster;
import com.monkey.demolist.greendao.n.DaoSession;

import java.util.List;

/**
* Description: 1:1查询(学生表和成绩表联表查询)
* Author: Arthor
* Date: 2017/10/23
* Time: 14:04
*/

public class OneVOneActivity extends AppCompatActivity {

    private static final String TAG = "OneVOneActivity";

    private ScoreBeanDao scoreBeanDao;
    private StudentBeanDao studentBeanDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_vone);

        // 初始化ScoreBean和StudentBean的DAO
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "grade.db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        scoreBeanDao = daoSession.getScoreBeanDao();
        studentBeanDao = daoSession.getStudentBeanDao();

        // 插入外键对应的ScoreBean
        ScoreBean scoreBean = new ScoreBean();
        scoreBean.setEnglishScore("120");
        scoreBean.setMathScore("150");
        scoreBeanDao.insert(scoreBean);

        // 插入外键对应的StudentBean
        StudentBean studentBean = new StudentBean();
        studentBean.setName("zone");
        studentBean.setStudentNum("123456");
        ScoreBean unique = scoreBeanDao.queryBuilder().unique();
        if (unique != null) {
            studentBean.setScoreId(unique.getId());
            studentBean.setMScoreBean(unique);
            studentBeanDao.insert(studentBean);
        }

        // 查询数据
        List<StudentBean> list = studentBeanDao.queryBuilder().list();
        for (int i = 0; i < list.size(); i++) {
            StudentBean bean = list.get(i);
            Log.e(TAG, "onCreate:" + bean.getId());
            Log.e(TAG, "onCreate:" + bean.getStudentNum());
            Log.e(TAG, "onCreate:" + bean.getName());
            Log.e(TAG, "onCreate:" + bean.getScoreId());
            Log.e(TAG, "onCreate:" + bean.getMScoreBean().getId());
            Log.e(TAG, "onCreate:" + bean.getMScoreBean().getMathScore());
            Log.e(TAG, "onCreate:" + bean.getMScoreBean().getEnglishScore());
        }
    }
}
